package fr.emn.integration.synthese.controle;

import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import fr.emn.integration.synthese.abstraction.Cours;

public class ControlJListGroupes implements Observer, ListSelectionListener {
	private JList liste;
	private Cours modele;

	public ControlJListGroupes(Cours modele, JList liste) {
		this.modele = modele;
		this.liste = liste;
		String[] data = { "-" };
		this.liste.setListData(data);
		this.liste.setSelectedIndex(0);
	}

	public void update(Observable o, Object message) {
		Integer iMessage = (Integer) message;
		if (iMessage == Cours.CHANGEMENT_MODULE_COURANT
				|| iMessage == Cours.CHANGEMENT_GROUPES) {
			int moduleCourante = this.modele.getModuleCourante();
			
			if (moduleCourante != -1) {
				Vector<String> data = this.modele.getGroupeNames(moduleCourante);
				data.add(0, "-");
				this.liste.setListData(data);
			} else {
				String[] data = { "-" };
				this.liste.setListData(data);
			}
			if (this.modele.getGroupeCourante() != -1){
				this.liste.setSelectedValue(String.valueOf(this.modele.getGroupeCourante()), true);
			}
			else
				this.liste.setSelectedIndex(0);
			this.liste.repaint();
		}
	}

	public void valueChanged(ListSelectionEvent e) {
		if (this.liste.getSelectedIndex() != -1
				&& !this.liste.getSelectedValue().equals("-")){
			this.modele.setGroupeCourante(modele.findGroupeId((String) this.liste.getSelectedValue(), modele.getModuleCourante()));
			
		}
		else if (this.liste.getSelectedIndex() != -1)
			this.modele.setGroupeCourante(-1);
	}
}